using System;
using System.IO;
using UnityEngine;

public class FileDataHandler
{
    private string fullPath;
    private bool isEncrpyData;
    private string codeWord = "Mozhihuang.com";

    public FileDataHandler(string path, string fileName,bool isEncrpyData)
    {
        this.isEncrpyData = isEncrpyData;
        fullPath = Path.Combine(path, fileName);
    }

    public void SaveData(GameData gameData)
    {
        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

            string dataToSave = JsonUtility.ToJson(gameData, true);

            if (isEncrpyData)
                dataToSave=EncryptDecrypt(dataToSave);
            using FileStream fileStream = new(fullPath, FileMode.Create);
            using StreamWriter streamWriter = new(fileStream);
            streamWriter.Write(dataToSave);
        }
        catch (Exception e)
        {
            Debug.LogError("Error on try to save data to file" + e.Message);
        }
    }
    public GameData LoadData()
    {
        GameData gameData = null;

        if (File.Exists(fullPath))
        {
            try
            {
                using FileStream fileStream = new(fullPath, FileMode.Open);
                using StreamReader streamReader = new(fileStream);
                string dataToLoad = streamReader.ReadToEnd();
                if (isEncrpyData)
                    dataToLoad = EncryptDecrypt(dataToLoad);
                gameData = JsonUtility.FromJson<GameData>(dataToLoad);
            }
            catch (Exception e)
            {
                Debug.LogError("Error on try to Load data from file" + e.Message);
            }
        }
        return gameData;
    }

    public void DeleteData()
    {
        if (File.Exists(fullPath))
            File.Delete(fullPath);
    }

    private string EncryptDecrypt(string data)
    {
        string modifedData = "";
        for (int i = 0; i < data.Length; i++)
        {
            // 获取当前位置的字符
            char originalChar = data[i];

            // 计算密钥中对应位置的索引（循环使用密钥）
            int keyIndex = i % codeWord.Length;

            // 获取密钥中对应位置的字符
            char keyChar = codeWord[keyIndex];

            // 进行异或运算（将字符转换为其ASCII码值进行运算）
            int xorResult = originalChar ^ keyChar;

            // 将运算结果转换回字符
            char modifiedChar = (char)xorResult;

            // 将处理后的字符添加到结果字符串中
            modifedData += modifiedChar;
        }

        return modifedData;
    }
}
